package com.qdsg.ysg.doctor.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.Gravity;
import android.widget.Toast;

import com.qdsg.ysg.doctor.eventbus.Logout;
import com.qdsg.ysg.doctor.ui.activity.mine.WxLoginActivity;
import com.rest.exception.BusinessException;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2020/2/9.
 */

public class ToastUtil {
    private static WeakReference<Context> contextWeakReference;

    private static Toast toast;

    public static void init(Context context) {
        contextWeakReference = new WeakReference<>(context);
    }

    public static void onError(Context context, Throwable e) {
        if (e instanceof BusinessException) {
            showToastCenter(context, ((BusinessException) e).errorDescription);
            if (((BusinessException) e).errorCode == 2030007 || ((BusinessException) e).errorCode == 20200001) {
                EventBus.getDefault().postSticky(new Logout(1));
                context.startActivity(new Intent(context, WxLoginActivity.class));
            }
        }
    }

    /**
     * 居中显示的
     */
    @SuppressLint("ShowToast")
    public static void showToastCenter(Context mContext, String msg) {
        if (toast == null) {
            toast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setText(msg);
        toast.show();
    }

    @SuppressLint("ShowToast")
    public static void showToast(Context mContext, String msg) {
        if (toast == null) {
            toast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
        }
        toast.setGravity(Gravity.CENTER, 0, 0); //在屏幕中间
        toast.setText(msg);
        toast.show();
    }

    /**
     * 在主线程显示吐司
     *
     * @param msg
     */
    public static void showToastOnUIThread(Context mContext, final String msg) {
        Handler handler = new Handler(mContext.getMainLooper());
        handler.post(() -> showToast(mContext, msg));
    }
}
